from machine import Pin
import time
from rotary_irq_esp import RotaryIRQ
import webrepl

from wifi import WiFi

import settings as st
from ui import UI
from battery import Battery


ok_btn = Pin(st.ROTARY_BTN, Pin.IN)
charge_detect = Pin(st.CHARGE_DETECT, Pin.IN)

def is_charging():
    return charge_detect.value() == 0

def main():
    bat = Battery(st.BATTERY_LEVEL)
    ui = UI()
    wifi = WiFi(st.WIFI_SSID, st.WIFI_PSK)

    rot = RotaryIRQ(pin_num_clk=st.ROTARY_CLK, 
              pin_num_dt=st.ROTARY_DT, 
              min_val=-2, 
              max_val=2, 
              reverse=False, 
              range_mode=RotaryIRQ.RANGE_WRAP)

    webrepl.start(password='123456')

    m = [
        ["Wi-Fi Lamp1", ""],
        ["Wi-Fi Lamp2", ""],
        ["Wi-Fi Lamp3", ""],
        ["Wi-Fi Lamp4", ""],
        ["Wi-Fi Lamp5", ""],
        ["Wi-Fi Lamp6", ""],
        ["Wi-Fi Lamp7", ""],
        ["Wi-Fi Lamp8", ""],
    ]

    ok_btn_status = 1
    charging_status = False
    sleep_counter = 0
    ui.init()
    ui.menu = m
    ui.draw_menu()
    ui.show_msg("Connecting","to Wi-Fi...")
    wifi.connect()
    while True:
        rotary_val = rot.value()
        battery_level = bat.get_level()
        if is_charging():
            if charging_status != is_charging():
                ui.draw_battery_charging()
                charging_status = is_charging()
                print("charging")
                ui.show_msg("Charging")
        else:
            if charging_status != is_charging():
                charging_status = is_charging()
                print("Discharging")
                ui.show_msg("Discharging")
            ui.draw_battery_level(battery_level)
        tmp = ok_btn.value()
        if ok_btn_status != tmp:
            sleep_counter = 0
            if tmp == 0:
                print(ui.menu_index)
            ok_btn_status = tmp
        if rotary_val != 0:
            sleep_counter = 0
            if rotary_val > 0:
                ui.menu_next()
            else:
                ui.menu_prev()
            rot.reset()
        ui.show()
        time.sleep_ms(10)
        sleep_counter += 1
        if sleep_counter >= 5000:
            ui.close()
            wifi.close()
            break

while True:
    main()
    while ok_btn.value() == 1:
        time.sleep(1)
    count = 0
    while ok_btn.value() == 0:
        time.sleep_ms(100)
        count += 1
        if count > 10:
            break